package vn.vfriends.mcms.site.service.impl;

import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import vn.vfriends.mcms.site.model.Site;
import vn.vfriends.mcms.site.service.SiteService;

/**
 *
 * @author tuan@vfriends.vn
 */
public class SiteJpaController implements SiteService {

    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "mcmsPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    @Override
    public Site findSiteByName(String name) {
        EntityManager em = getEntityManager();
        try {
            Query query = em.createNamedQuery("Site.findByName", Site.class);
            query.setParameter("name", name);
            List<Site> siteList = (List<Site>) query.getResultList();
            if (siteList != null && !siteList.isEmpty()) {
                return siteList.get(0);
            } else {
                return null;
            }
        } finally {
            em.close();
        }
    }
}
